import { createReducer } from './util';
import * as RunnableGroupAction from '../actions/runnable-group';
import _ from 'lodash';

export const currentUserRunnableGroupList = createReducer(on => {
  on(RunnableGroupAction.listByCurrentUser);
}, []);

export const runnableGroup = createReducer(on => {
  on(RunnableGroupAction.get);
  on(RunnableGroupAction.createRuntime)
    .completed((state, action) => {
      const oldRuntimes = state.runnableRuntimes || [];
      const runnableRuntimes = _.concat(oldRuntimes, action.payload);
      return Object.assign({}, state, { runnableRuntimes });
    });
  on(RunnableGroupAction.deleteRuntime)
    .completed((state, action) => {
      const runnableRuntimes = state.runnableRuntimes.filter(runtime => runtime.id !== action.payload);
      return Object.assign({}, state, { runnableRuntimes });
    });
  on(RunnableGroupAction.renameRuntime)
    .completed((state, action) => {
      const { runtimeId, name } = action.payload;
      const runnableRuntimes = state.runnableRuntimes.map(runtime => {
        if (runtime.id === runtimeId) {
          return Object.assign({}, runtime, { name });
        }
        return runtime;
      });
      return Object.assign({}, state, { runnableRuntimes });
    });
}, {});

export const groupMachines = createReducer(on => {
  on(RunnableGroupAction.listGroupMachines);
}, []);


export const runnableGroupList = createReducer(on => {
  on(RunnableGroupAction.search);
}, {
  currentPage: 0,
  total: 0,
  list: []
});
